const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');

// 创建Express应用
const app = express();
const port = 3000;

// 中间件
app.use(bodyParser.json());
app.use(cors());
// 配置静态文件目录
app.use(express.static(path.join(__dirname, '../public')));

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'login',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 测试数据库连接
async function testDbConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
  } catch (error) {
    console.error('数据库连接失败:', error);
    process.exit(1);
  }
}

// 初始化数据库
async function initDatabase() {
  try {
    // 检查users表是否存在
      const [rows] = await pool.execute(`
      SELECT TABLE_NAME 
      FROM information_schema.TABLES 
      WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users'
    `, ['login']);

    if (rows.length === 0) {
      console.log('创建users表...');
      await pool.execute(`
        CREATE TABLE users (
          id INT NOT NULL AUTO_INCREMENT,
          email VARCHAR(255) NOT NULL UNIQUE,
          password_hash VARCHAR(255) NOT NULL,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
      `);
      console.log('users表创建成功');
    } else {
      console.log('users表已存在');
    }

    // 检查books表是否存在
    const [bookRows] = await pool.execute(`
      SELECT TABLE_NAME 
      FROM information_schema.TABLES 
      WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'books'
    `, ['login']);
    if (bookRows.length === 0) {
      console.log('创建books表...');
      await pool.execute(`
        CREATE TABLE books (
          id INT NOT NULL AUTO_INCREMENT,
          title VARCHAR(255) NOT NULL,
          author VARCHAR(255) NOT NULL,
          description TEXT,
          status ENUM('available', 'checked_out') DEFAULT 'available',
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
      `);
      console.log('books表创建成功');
    } else {
      console.log('books表已存在');
    }

  } catch (error) {
    console.error('初始化数据库失败:', error);
    process.exit(1);
  }
}

// 引入登录和注册API
const loginRoutes = require('./api/login.js');
const bookRoutes = require('./api/book.js');

// 根路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/login.html'));
});

// 启动服务器
async function startServer() {
  await testDbConnection();
  await initDatabase();

  // 注册路由和传递依赖
  loginRoutes(app, pool, bcrypt);
  bookRoutes(app, pool);

  app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
  });
} 

// web服务器   监听端口  http  映射接口

startServer();